/**
 * @description 本地缓存,有些是库显示一次，有些是库在当前用户显示一次
 */
import utils from 'utils';

export function setCachedRepoId(key, type) {
  const ids = getCachedRepoIds(key);
  const valueItem = getCachedRepoValue(type);
  if (!ids.includes(valueItem)) {
    ids.push(valueItem);
  }
  utils.setCachedData(key, JSON.stringify(ids));
}

/**
 * 获取要设置的缓存值
 * @param {*} type repo 库显示一次；repo_user:库在当前用户显示一次; user 只和用户相关
 */
export function getCachedRepoValue(type = 'repo') {
  const { pathResource, user } = window.FORCE;
  if (type === 'user') {
    return `${user.codeUserId}`;
  } else if (type === 'repo_user') {
    return `${pathResource.id}_${user.codeUserId}`;
  } else {
    return `${pathResource.id}`;
  }
}

export function getCachedRepoIds(key) {
  const curIdStr = utils.getCachedData(key);
  if (curIdStr) {
    return JSON.parse(curIdStr);
  }
  return [];
}

export function hasCachedRepoId(key, type) {
  return getCachedRepoIds(key).includes(getCachedRepoValue(type));
}

export default {
  setCachedRepoId,
  getCachedRepoValue,
  hasCachedRepoId,
  getCachedRepoIds,
};
